package com.huyframe.Presenter;

import android.content.Context;

import com.google.gson.Gson;
import com.huyframe.model.bean.GankDateModel;
import com.huyframe.model.http.Api;
import com.huyframe.model.manager.RetrofitUtil;
import com.huyframe.view.test.MainView;
import com.orhanobut.logger.Logger;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by BillLamian on 2016/7/13.
 */
public class MainPresenter extends BasePresenter<MainView>{

    private Api api;
    private Context context;
    private Subscription subscription;

    public MainPresenter(Context context){
        this.context=context;
        api= RetrofitUtil.create(context,Api.class);
    }

    @Override
    public void attachView(MainView view) {
        super.attachView(view);
    }

    @Override
    public void detachView() {
        super.detachView();
        if(subscription!=null){
            subscription.unsubscribe();
        }
    }

    @Override
    public MainView getHuyView() {
        return super.getHuyView();
    }


    public void loadDatas(String type,int pageSize,int pageNum){
        checkViewAttached();
        subscription=api.getData(type,pageSize,pageNum)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        getHuyView().showLoading("正在加载数据...");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GankDateModel>() {
                    @Override
                    public void onCompleted() {
                        getHuyView().hideLoading();
                    }


                    @Override
                    public void onError(Throwable e) {
                        getHuyView().showError(e.getMessage(),null);
//                        Logger.e(e.getMessage(),"Test");
                    }

                    @Override
                    public void onNext(GankDateModel info) {
                        Logger.json(new Gson().toJson(info));
                        getHuyView().loadData(info);
                    }
                });

    }


}
